<?php
	set_time_limit(60*60);
	ini_set('memory_limit', '128M');


	require_once "config.php";
	require_once dirname(__FILE__). '/util/connection.class.php';
	require_once dirname(__FILE__). '/util/TimeUtil.php';
	require_once dirname(__FILE__). '/util/record.php';
	
	
	$tag = '';
	if(TimeUtil::isAnotherMonth()){
		$tag = 'monthly';
	}elseif(TimeUtil::isAnotherWeek()){
		$tag = 'weekly';
	}else{
		$tag = 'daily';
	}
	$dbconn = Connection::getInstance();
	
	$users = getUsers($dbconn);
	foreach ($users as $user){
		addNewEmail($tag, $user['template'], array('username'=>$user['name'], 'email'=>$user['email'], 'uid'=>$user['id']), $dbconn);
	}
	
	
	
	function getUsers(Connection $db){
		$sql = "select u.id, u.email, concat(u.firstname, ' ', u.lastname)as name, s.template from users as u left join sites as s on u.site_id=s.id where created <=" . (time()- 432000);
		try{
			return $db->query($sql);
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	


	function getTemplate($tag, $site_template){
		$template_name = TEMPLATE_ROOT .'/'.$site_template . '/email/' . $tag . '.html';
		if(file_exists($template_name)){
			if(is_readable($template_name)){
				$template = file_get_contents($template_name);
				return $template;
			}
		}
	}
	
	function addNewEmail($tag, $site_template, $args, $db){
		if($template = getTemplate($tag, $site_template)){
			$content = translateTemplate($template,  $args);
			$subject = getEmailSubject($tag, $site_template, $args);
			if(addSentEmailToDb($site_template, 'no-reply@' . strtolower($args['domain']), $subject, $args['email'], $content, 0, $db)){
				$record = new Record($args['uid']);
				$record->addEmailSentRecording($tag);
				return true;
			}
		}
		return false;		
	}
	
	function addSentEmailToDb($sender, $sendfrom, $subject, $sendto, $content, $sent=0, Connection $db){
		$sql = "insert into emails set sender=?, sendfrom=?, subject=?, sendto=?, content=?, created=?, sent=?";
		try{
			return $db->execute($sql,array($sender, $sendfrom, $subject, $sendto, $content, time(), $sent));
		}catch (Exception $e){
			QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
			throw new Model_Exception($e->getMessage(), $e->getCode());
		}
	}
	
	function translateTemplate($content, $args){
		foreach ($args as $k => $v){
			$content = str_replace('[[' . $k . ']]', $v, $content);
		}
		return $content;
	}
	
	function getEmailSubject($tag, $site_template, $args){
		$config = TEMPLATE_ROOT .'/'.$site_template . '/email/email.ini';
		$subjects = parse_ini_file($config);
		$subject = isset($subjects[$tag]) ? $subjects[$tag] :false;
		if($subject){
			return translateTemplate($subject, $args);
		}
		return '';
	}